package com.jjh.back.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.jjh.common.pojo.InfoEnum;
import com.jjh.common.servlet.BaseServlet;
import com.jjh.common.util.ConstatFinalUtil;
import com.jjh.common.util.PageInfoUtil;
import com.jjh.users.pojo.AAdmins;
import com.jjh.users.pojo.ALog;
import com.jjh.users.pojo.ALogEnum;
import com.jjh.users.pojo.ARole;
import com.jjh.users.service.IAuthDbService;
import com.jjh.users.service.IUsersDbService;

/**
 * 登陆后访问的页面
 * 只是管理员访问的页面
 * @author Zjx
 */
@Controller
@RequestMapping("/back/admin")
@MultipartConfig
public class AdminsBackServlet extends BaseServlet
{
	@Autowired
	private IAuthDbService authDbService ;
	@Autowired
	private IUsersDbService usersDbService ;
	

	@RequestMapping("/roleList")
	private String roleList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		System.out.println("==roleList====");
		/* 分页工具类 */
		PageInfoUtil pageInfoUtil = proccedPageInfoUtil(request);
		/* 处理搜索条件 */
		Map<String,Object> condMap = proccedSearchCond(request);
		
		List<ARole> roleList = this.usersDbService.findCondListRoleService(pageInfoUtil, condMap);
		/* 存储到四大作用域中 */
		request.setAttribute("list", roleList);
		request.setAttribute("pageInfoUtil", pageInfoUtil);
		
		/* 服务端跳转页面 */
		return "/back/admins/roleList" ;
	}

	/**
	 * 更新提交操作
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping(value = "adminsUpdateSubmit",produces = "text/html;charset=UTF-8" )
	@ResponseBody
	private String adminsUpdateSubmit(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		System.out.println("==adminsUpdate===");
		/* 根据id查询管理员 */
		String id = request.getParameter("id");
		Map<String,Object> condMap = new HashMap<String, Object>();
		condMap.put("id", id);
		condMap.put("extend","true");
		AAdmins admins = this.usersDbService.findOneAdminsService(condMap);
		/* 我们要跳转页面,所以把admins信息放到request中;因为要在页面上显示 */
		request.setAttribute("one", admins);
		
		Map<String,Object> fileMap = new HashMap<String, Object>();
		boolean updateFlag = false ;
		/* 接收参数,做区分 */
		String operType = request.getParameter("operType");
		if("adminsUpdateInfo".equalsIgnoreCase(operType))
		{
			// 修改个人信息
			/* 接收参数 */
			//修改个人信息
			/* 接收参数  */
			String roleId = request.getParameter("roleId");
			String email = request.getParameter("email");
			String trueName = request.getParameter("trueName");
			String qq = request.getParameter("qq");
			String phone = request.getParameter("phone");
			/* sex:接收的时候是字符串,但是在pojo中byte类型;处理参数的目标对象 */
			String sex = request.getParameter("sex");
			String status = request.getParameter("status");
			/* 处理参数 */
			int roleIdInt = Integer.parseInt(roleId);
			byte sexByte = Byte.parseByte(sex);
			byte statusByte = Byte.parseByte(status);
			/* 为对象赋值 */
			admins.setRoleId(roleIdInt);
			admins.setEmail(email);
			admins.setTrueName(trueName);
			admins.setQq(qq);
			admins.setPhone(phone);
			admins.setSex(sexByte);
			admins.setStatus(statusByte);
			
			/* 接收图片 */
			Part part = request.getPart("file");
			if(part != null && part.getSubmittedFileName() != null)
			{
				InputStream is = part.getInputStream();
				fileMap.put("is", is);
				fileMap.put("fileName", part.getSubmittedFileName());
			}
			updateFlag = true ; 
		}else if("adminsResetPass".equalsIgnoreCase(operType))
		{
			// 重置密码
			String password = request.getParameter("password");
			/* 密码加密 */
			admins.setPassword(this.enuEncryptUtil.encodeStr(password));
			updateFlag = true ;  
		}
		
		JSONObject resultJSON = new JSONObject();
		/* 更新数据库 */
		if(updateFlag)
		{
			/* 要更新数据库 */
			resultJSON = this.usersDbService.updateOneAdminsService(admins,fileMap);
		}else
		{
			/* 操作失败 */
			resultJSON.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_OPER_ERROR.getCode());
			resultJSON.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.getString(InfoEnum.INFO_OPER_ERROR.getCode() + ""));
		}
		
		return resultJSON.toJSONString();
	}

	/**
	 * 打开管理员更新页面
	 * 		修改个人信息(不包含密码)/adminsUpdate(需要修改service方法)
	 * 		重置密码;method=adminsResetPass
	 * 		查看个人信息,不修改;method=adminsInfo
	 * 
	 * 额外增加一个参数:operType(这种方法)
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping("/adminsUpdate")
	private String adminsUpdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		System.out.println("==adminsUpdate===");
		/* 根据id查询管理员 */
		String id = request.getParameter("id");
		Map<String,Object> condMap = new HashMap<String, Object>();
		condMap.put("id", id);
		condMap.put("extend","true");
		AAdmins admins = this.usersDbService.findOneAdminsService(condMap);
		/* 我们要跳转页面,所以把admins信息放到request中;因为要在页面上显示 */
		request.setAttribute("one", admins);
		
		/* 路径 */
		String path = "" ; 
		/* 接收参数,做区分 */
		String operType = request.getParameter("operType");
		if("adminsUpdateInfo".equalsIgnoreCase(operType))
		{
			/* 查询所有状态为启用的角色(不能分页);前题我们得清楚记录不是很多
			 * 应该是角色的枚举(模仿着管理员的枚举写一个角色的枚举呢???)
			 *  */
			condMap.clear();
			condMap.put("status", "1");
			List<ARole> roleList = this.usersDbService.findCondListRoleService(null, condMap);
			request.setAttribute("roleList", roleList);
			/* 打开更新个人信息页面 */
			return "/back/admins/adminsUpdateInfo" ; 
		}else if("adminsResetPass".equalsIgnoreCase(operType))
		{
			/* 重置密码 */
			return "/back/admins/adminsResetPass" ;
		}
		/* 很low,但是很安全
		 * 因为要把服务端跳转变成客户端跳转,心里得有数
		 * 修改Servlet代码;就要知道所有的request.setAttribute()已经不好使用了;可以显式的更换;
		 *  */
		//request.setAttribute("operType", operType);
		//this.serverRedirect(request, response, path);
		
		return "/back/admins/adminsInfo" ;
	}

	/**
	 * 管理员添加提交操作
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	@RequestMapping(value = "adminsInsertSubmit",produces = "text/html;charset=UTF-8" )
	@ResponseBody
	private String adminsInsertSubmit(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		System.out.println("==adminsInsertSubmit===");
		/* 接收参数 */
		String roleId = request.getParameter("roleId");
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		String trueName = request.getParameter("trueName");
		String qq = request.getParameter("qq");
		String phone = request.getParameter("phone");
		/* 接收的时候是字符串 要转换成整型 处理目标参数对象 */
		String sex = request.getParameter("sex");
		String status = request.getParameter("status");
		/* 处理参数 */
		int roleIdInt = Integer.valueOf(roleId);
		byte sexByte = Byte.valueOf(sex);
		byte statusByte = Byte.valueOf(status);
		/* 为对象赋值 */
		AAdmins admins = new AAdmins();
		admins.setRoleId(roleIdInt);
		admins.setEmail(email);
		admins.setPassword(password);
		admins.setTrueName(trueName);
		admins.setQq(qq);
		admins.setPhone(phone);
		admins.setSex(sexByte);
		admins.setStatus(statusByte);
		/* 调用Service方法 */
		JSONObject resultJSON = this.usersDbService.saveOneAdminsService(admins);
		/* 存储Service方法执行结果,目的是为了要把结果通知给jsp */
		/*  响应是json */
		//this.printStr(request, response, resultJSON.toJSONString());
		return resultJSON.toJSONString();
	}

	/**
	 * 打开管理员添加页面
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping("/adminsInsert")
	private String adminsInsert(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		System.out.println("==adminsInsert===");
		Map<String,Object> condMap = new HashMap<String, Object>();
		/* 查询所有状态为启用的角色(不能分页);前题我们得清楚记录不是很多
		 * 应该是角色的枚举(模仿着管理员的枚举写一个角色的枚举呢???)
		 *  */
		condMap.clear();
		condMap.put("status", "1");
		List<ARole> roleList = this.usersDbService.findCondListRoleService(null, condMap);
		request.setAttribute("roleList", roleList);
		/* 直接跳转到管理员添加页面中 */
		return "/back/admins/adminsInsert" ;
	}

	/**
	 * 管理员列表
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping("/adminsList")
	private String adminsList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		System.out.println("==AdminsBackServlet==adminsList");
		/* 分页工具类 */
		PageInfoUtil pageInfoUtil = proccedPageInfoUtil(request);
		/* 处理搜索条件 */
		Map<String, Object> condMap = proccedSearchCond(request);
		
		/* ==性别处理开始== */
		String sex = request.getParameter("sex");
		if(sex == null)
		{
			sex = "" ; 
		}
		condMap.put("sex", sex);
		request.setAttribute("sex", sex);
		/* ==性别处理结束== */
		
		/* ==roleId处理开始== */
		String roleId = request.getParameter("roleId");
		if(roleId == null)
		{
			roleId = "" ; 
		}
		condMap.put("roleId", roleId);
		request.setAttribute("roleId", roleId);
		/* ==roleId处理结束== */
		
		List<AAdmins> adminsList = this.usersDbService.findCondListAdminsService(pageInfoUtil,condMap);
		/* 存储四大作用域 */
		request.setAttribute("list", adminsList);
		request.setAttribute("pageInfoUtil", pageInfoUtil);
		
		/* 查询所有状态为启用的角色(不能分页);前题我们得清楚记录不是很多
		 * 应该是角色的枚举(模仿着管理员的枚举写一个角色的枚举呢???)
		 *  */
		condMap.clear();
		condMap.put("status", "1");
		List<ARole> roleList = this.usersDbService.findCondListRoleService(null, condMap);
		request.setAttribute("roleList", roleList);
		
		/* 服务端跳转页面 */
		return "/back/admins/adminsList" ;
	}

	/**
	 * 退出
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping("/logout")
	private String logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		HttpSession session = request.getSession() ; 
		String ip = request.getRemoteAddr();
		AAdmins admins = (AAdmins) session.getAttribute("adminsSess");
		session.removeAttribute("lastLoginTime");
		session.removeAttribute("adminsSess");
		
		/* 记录日志 */
		ALog log = new ALog();
		log.setAdminsId(admins.getId());
		log.setLogType(ALogEnum.TYPE_LOGOUT.getCode());
		log.setIp(ip);
		log.setContent(admins.getEmail() + "----退出系统;");
		log.setStatus(ALogEnum.STATUS_ENABLED.getCode());
		
		log.setPubTime(new Date());
		this.usersDbService.saveOneLogService(log);
		
		/* 客户端跳转 */
		return "redirect:/login"; 
	}

	/**
	 * 欢迎页面
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping("/welcome")
	private String welcome(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		return "/back/admins/welcome" ;
	}

	/**
	 * 登陆后首页
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping("/main")
	private String main(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		/* 服务器端跳转 */
		return "/back/admins/main" ;
	}
}
